#encoding=utf-8
from __future__ import division

import sys
import os
import datetime
import time
import math
import ujson
import uuid
import urllib
import traceback
from urlparse import urlparse, parse_qsl

import requests
from django.contrib import auth
from django.template import RequestContext
from django.core.cache import cache
from django_redis import get_redis_connection
from django.core.servers.basehttp import FileWrapper
from django.http import StreamingHttpResponse
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User
from django.db.models import Count, Max, F, Q,Sum
from django.db import transaction
from django.contrib.auth.decorators import login_required
from django.shortcuts import render

from andy_manager import settings
from websys.models import (
    UserInfo,AgentInfo,AgentRecharge,UserRecharge,CommissionReport,UserConsumeRecord,PlatformInfo,
)

import  websys.fun as fun

from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
                    #代理折扣
                    url(r'^discount', 'websys.view.recharge.get_agentdiscount', name='agentdiscount'),
                       #代理充值
                    url(r'^oper', 'websys.view.recharge.op_gamepoint', name='op_gamepoint'),
                    url(r'^com', 'websys.view.recharge.op_sync_commission', name='op_commission'),
                       url(r'^test', 'websys.view.recharge.testpoint', name='testpoint'),

    )
#http://127.0.0.1:8080/api/recharge/discount?uid=1&type=0&gameid=1
#uid帐号，type为0代理，1玩家
@csrf_exempt
def get_agentdiscount(request):
    ret = {"ret": 0, "msg": "","discount":1}
    _id = request.GET["uid"]
    act = int(request.GET["type"])
    #是否存在
    if act==0 and AgentInfo.objects.filter(pk=_id).exists():
        record = AgentInfo.objects.get(pk=_id)
        ret['discount']=record.discount
    else:
        pass

    return HttpResponse(ujson.dumps(ret))

#平台列表
APP_LIST=[]
def GetPlatformList():
    pis=PlatformInfo.objects.all()
    for ii_pi in pis:
        APP_LIST.append(ii_pi.pf_id)
GetPlatformList()

#http://127.0.0.1:8080/api/recharge/oper?uid=1&type=1&money=70&amount=100&gameid=1&order_id=123&out_order_id=4008201705026123456&paytype=0&gamedata={}
#uid帐号，type为0代理，1玩家,money实际扣的钱，amount增加的数量,gameid游戏编号,order_id订单号，paytype支付方式，gamedata游戏请求
#{u'gameid': u'nhmj123', u'uid': u'114', u'order_id': u'c35532f641e311e787a25254003a3385', u'money': u'0.01', u'paytype': u'1',
# u'gamedata': u"{u'diamond': 100}", u'amount': u'0', u'type': u'1'}
@csrf_exempt
def op_gamepoint(request):
    ret = {"ret": -10, "msg": ""}
    diamond_arr=[100,1050,5600,13000]
    game_arr=APP_LIST#['nhmj123','xsmj123']
    try:
        t_obj=request.GET.dict()
        fun.add_log(t_obj,'','re_')

        t_id = request.GET["uid"]
        t_act = int(request.GET["type"])
        t_money=request.GET["money"]
        t_amount=int(request.GET["amount"])#游戏金币
        t_gid=request.GET["gameid"]
        t_type=int(request.GET["paytype"])
        t_order=request.GET["order_id"]
        t_gamedata=request.GET["gamedata"]
        t_out_order=request.GET["out_order_id"]
        #print t_gid,'========================',game_arr
        if (t_act not in [0,1]) or (t_gid not in game_arr):
            ret["ret"] = -1
            ret["msg"] = "error parms"
            return HttpResponse(ujson.dumps(ret))
        #处理游戏的数据
        game_obj=ujson.loads(t_gamedata)
        t_amount=game_obj['diamond']

        if int(t_amount) not in diamond_arr :
            ret["ret"] = -2
            ret["msg"] = "error diamond"
            return HttpResponse(ujson.dumps(ret))

        with transaction.commit_on_success():
            #是否存在
            if t_act==0 and AgentInfo.objects.filter(pk=t_id).exists():#代理
                record = AgentInfo.objects.get(pk=t_id)
                record.gamepoint+=t_amount
                record.save()
                #根据数量找返利

                #添加记录
                ar=AgentRecharge()
                ar.agentid=t_id
                ar.username=record.username
                ar.amount=t_amount
                ar.money=t_money
                ar.lastpoint=record.gamepoint
                ar.save()
            if t_act==1 and UserInfo.objects.filter(pk=t_id).exists():#玩家
                #订单号是否重复
                t_count=UserRecharge.objects.filter(Q(out_orderid=t_out_order)|Q(orderid=t_order)).count()
                if t_count>0:
                    ret["ret"] = -3
                    ret["msg"] = "repeat orderid-"+str(t_count)
                else:
                    uobj = UserInfo.objects.get(pk=t_id)
                    uobj.gamepoint+=t_amount
                    uobj.save()
                    #添加记录
                    ur=UserRecharge()
                    ur.uid_id=t_id
                    ur.nickname=uobj.nickname
                    ur.amount=t_amount
                    ur.lastpoint=uobj.gamepoint
                    ur.out_orderid=t_out_order
                    ur.appid=t_gid

                    ur.gamedata=t_gamedata
                    ur.orderid=t_order
                    ur.paytype=t_type
                    ur.money=t_money
                    ur.classid=''
                    #代理级别
                    if(uobj.agentid):
                        ur.classid=uobj.agentid.classid
                    ur.save()
                    #流水消费表
                    ucr=UserConsumeRecord()
                    ucr.gameid=0
                    ucr.typeid=10+int(t_type)
                    ucr.consumepoint=t_amount
                    ucr.lastpoint=uobj.gamepoint
                    ucr.uid_id=t_id
                    ucr.remark=t_gid+'_pay'
                    ucr.requestkey=t_order
                    ucr.save()
                    ret["ret"] = 0
                    ret['msg']='success'
            else:
                ret["ret"] = -5
                ret["msg"] = "error uid"
    except Exception, e:
        #fun.add_log(e,'error')
        print request
        fun.add_log_err(request.get_full_path()+'---'+traceback.format_exc())
        ret["ret"] = -20

    return HttpResponse(ujson.dumps(ret))

LAST_TIME=datetime.datetime.now()
TIME_SECONDS=60#有人充值1分钟跑一次
@csrf_exempt
#http://127.0.0.1:8080/api/recharge/com
def op_sync_commission(request):
    ret = {"ret": 0, "msg": ""}

    t_obj={}#帐号_日期为key
    #获取没操作的
    date_now=datetime.datetime.now()
    cur_hour=datetime.datetime.now().strftime('%H')
    global LAST_TIME,TIME_SECONDS
    if(date_now-LAST_TIME).seconds<TIME_SECONDS:
        ret = {"ret": -1, "msg": "not to time"}
        return HttpResponse(ujson.dumps(ret))
    else:
        fun.add_log('com sync','','re_')
        LAST_TIME=date_now

    date_now=date_now.strftime('%Y-%m-%d %H:%M:%S')
    date_end=datetime.date.today()
    date_start=date_end + datetime.timedelta(-1)
    for cur_date in [date_start,date_end]:
        t_date=cur_date.strftime('%Y-%m-%d')
        #t_date='2017-05-26'
        date_00=t_date+' 00:00:00'
        date_24=t_date+' 23:59:59'
        if date_end==cur_date:
            date_24=date_now
        #17.8.15加上平台汇总
        t_data=UserRecharge.objects.filter(is_sync=0,create_time__range=(date_00,date_24)).values("classid","paytype","appid").annotate(money=Sum('money'))

        #t_data=UserRecharge.objects.filter(is_sync=0).values("id","uid","classid","money","paytype","create_time").order_by("id")
        for ii in t_data:
            t_cid=ii['classid']
            #t_date=ii['create_time'].strftime('%Y-%m-%d')
            t_key=ii['appid']+"_"+t_date+"_"+str(ii['paytype'])+"_"
            t_money=ii["money"]
            if len(t_cid)==0:#无代理
                if t_key not in t_obj:
                    t_obj[t_key]=[t_money,t_money]
                else:
                    t_obj[t_key][0]+=t_money
                    t_obj[t_key][1]+=t_money
            else:#遍历级别的代理100101102103
                if len(t_cid)==3:#一级代理的
                    ag_info=AgentInfo.objects.get(classid=t_cid)
                    t_rate=ag_info.comrate or 0
                    t_key_2=t_key+ag_info.account+"_"+t_cid
                    if t_key_2 not in t_obj:
                        t_obj[t_key_2]=[t_money,t_money*t_rate]
                    else:
                        t_obj[t_key_2][0]+=t_money
                        t_obj[t_key_2][1]+=t_money*t_rate
                    #系统的
                    if t_key not in t_obj:
                        t_obj[t_key]=[t_money,t_money*(1-t_rate)]
                    else:
                        t_obj[t_key][0]+=t_money
                        t_obj[t_key][1]+=t_money*(1-t_rate)
                    print t_cid,'-------------------',t_rate,t_money
                else:#多层代理
                    next_rate=0
                    while len(t_cid)>1:
                        #处理当级的
                        ag_info=AgentInfo.objects.get(classid=t_cid)
                        t_rate=ag_info.comrate or 0
                        t_key_2=t_key+ag_info.account+"_"+t_cid
                        if t_key_2 not in t_obj:
                            t_obj[t_key_2]=[t_money,t_money*(t_rate-next_rate)]
                        else:
                            t_obj[t_key_2][0]+=t_money
                            t_obj[t_key_2][1]+=t_money*(t_rate-next_rate)

                        t_cid=t_cid[0:len(t_cid)-3]
                        next_rate=t_rate
                    #系统的
                    if t_key not in t_obj:
                        t_obj[t_key]=[t_money,t_money*(1-next_rate)]
                    else:
                        t_obj[t_key][0]+=t_money
                        t_obj[t_key][1]+=t_money*(1-next_rate)
                    #print t_cid,'********************',t_rate,t_money
    #插入结帐表
    #{'2017-05-17_0_': [980, 508.0], '2017-05-17_0_a_100': [240, 72.0], '2017-05-17_1_a_100': [520, 113.0], '2017-05-17_1_': [1240, 796.0], '2017-05-17_0_a3_104': [300, 180.0], '2017-05-17_1_b22_103100': [330, 66.0], '2017-05-17_1_b_100100': [430, 43.0], '2017-05-17_0_a1_102': [440, 220.0], '2017-05-17_1_a2_103': [720, 222.0]}
    if len(t_obj)>0:
        try:
            with transaction.commit_on_success():
                for ikey in t_obj.keys():
                    tmp_arr=ikey.split('_')
                    t_appid=tmp_arr[0]
                    t_pdate=tmp_arr[1]
                    t_ptype=tmp_arr[2]
                    t_account=tmp_arr[3]
                    is_agent=(len(tmp_arr)>4)#代理
                    #是否存在
                    is_in=CommissionReport.objects.filter(pay_date=t_pdate,paytype=t_ptype,account=t_account,appid=t_appid).exists()
                    if is_in:
                        cr=CommissionReport.objects.get(pay_date=t_pdate,paytype=t_ptype,account=t_account,appid=t_appid)
                        cr.money+=t_obj[ikey][0]
                        cr.commission+=t_obj[ikey][1]
                    else:
                        cr=CommissionReport()
                        if is_agent:#代理
                            cr.account=t_account
                            cr.classid=tmp_arr[4]

                        cr.money=t_obj[ikey][0]
                        cr.commission=t_obj[ikey][1]
                        cr.paytype=t_ptype
                        cr.pay_date=t_pdate
                        cr.appid=t_appid
                    cr.save()
                    #代理表
                    if is_agent:
                        ag_info=AgentInfo.objects.get(classid=tmp_arr[4])
                        ag_info.allmoney+=t_obj[ikey][1]
                        ag_info.lastmoney+=t_obj[ikey][1]
                        ag_info.save()

                #更新数据库
                date_00=date_start.strftime('%Y-%m-%d')
                UserRecharge.objects.filter(is_sync=0,create_time__range=(date_00,date_now)).update(is_sync=1)
        except Exception, e:
            #fun.add_log(e,'error')
            #fun.add_log(traceback.print_exc())
            fun.add_log_err(traceback.format_exc())
            ret["ret"] = -2

    ret['data']=t_obj

    return HttpResponse(ujson.dumps(ret))

@csrf_exempt
def testpoint(request):
    ret = {"ret": 0, "msg": ""}
    import urllib
    import urllib2
    import uuid

    app_arr=['nhmj123','xsmj123']
    for ii in range(21,32):
        url = "http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"
        parm='amount=0&gameid=nhmj123&uid=8463&order_id=7ceb02b87b4611e78df200163e0e75c3&money=1.0&type=1&paytype=1&gamedata=%7B%22diamond%22%3A100%7D&out_order_id=4000662001201708074984408942'
        t_type=ii%2
        t_orderid='%s_%s'%(str(time.time()),str(ii))
        url="http://192.168.1.88:8080/api/recharge/oper?uid="+str(ii)+"&type=1&money="+str((ii/2)*10)+"&amount="+str(ii*5)+"&gameid="+app_arr[t_type]+"&order_id="+str(uuid.uuid1())+"&paytype="+str(t_type)+"&gamedata=%7B%22diamond%22%3A100%7D&&out_order_id="+t_orderid
        req = urllib2.Request(url)
        #print req

        res_data = urllib2.urlopen(req)
        res = res_data.read()
        print res
    return HttpResponse(ujson.dumps(ret))

def agent_settle(request):
    return render(request, 'xadmin/base_site.html', {'string': ''})
    return render(request, 'index.html', {'string': ''})